<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="14" :offset="4">
        <el-form ref="addForm" :rules="rules" :model="addForm" label-width="80px">
          <el-form-item label="商品名称" prop="shopName">
            <el-input v-model="addForm.shopName"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="shopPrice">
            <el-input v-model="addForm.shopPrice"></el-input>
          </el-form-item>
          <el-form-item label="商品类型" prop="shopType">
            <el-select v-model="addForm.shopType" placeholder="请选择商品类型">
              <el-option v-for="i in shopTypes" :label="i.name" :value="i.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品产地" prop="shopAddr">
            <el-input v-model="addForm.shopAddr"></el-input>
          </el-form-item>
          <el-form-item label="商品规格" prop="shopUnit">
            <el-input v-model="addForm.shopUnit"></el-input>
          </el-form-item>
          <el-form-item label="商品描述">
            <el-input type="textarea" v-model="addForm.shopRemark"></el-input>
          </el-form-item>
          <el-form-item label="上传图片">
            <el-upload
              list-type="picture-card"
              action="#"
              :limit="6"
              :auto-upload="false"
              :accept="accept"
              :on-change="changeImag"
              :on-exceed="handleExceed"
              :file-list="fileList"
              :before-remove="beforeRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('addForm')">立即创建</el-button>
            <el-button @click="resetForm('addForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>

    </el-row>

  </div>
</template>

<script>
  export default {
    name: "AddShop",
    data() {
      return {
        accept: ".jpg,.png",//上传格式限制
        addForm: {
          shopName: "",
          shopPrice: "",
          shopType: "",
          shopAddr: "",
          shopUnit: "",
          shopRemark: "",
        }, //商品数据
        fileList: [],//保存文件数据
        shopTypes: [],//加载商品分类
        rules: {
          shopName: [
            {required: true, message: '请输入商品名称', trigger: 'blur'}
          ],
          shopPrice: [
            {required: true, message: '请输入商品价格', trigger: 'blur'},
            {
              pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
              message: '请输入正确金额格式,可保留两位小数'
            },
          ],
          shopType: [{required: true, message: '请选择商品类型', trigger: 'change'}],
          shopAddr: [{required: true, message: '请输入商品地址', trigger: 'blur'}],
          shopUnit: [
            {required: true, message: '请输入商品规格', trigger: 'blur'},
            {min: 1, max: 2, message: '长度在 1 到 2 个字符', trigger: 'blur'}
          ]
        },//表单规则
      }
    },
    methods: {
      getShopTypes() {
        //获取类别
        this.$axios.get("shopType/shopType.action")
          .then(res => {
            this.shopTypes = res.data;
          })
          .catch(err => {
            this.$message.warning(err);
            alert(err)
          })

      },
      changeImag(file, fileList) {
        //获取文件信息
        this.fileList = fileList;
      },
      submitForm(formName) {
        //提交表单
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var formData = new FormData();
            //组装普通数据
            Object.keys(this.addForm).forEach((key) => {
              formData.append(key, this.addForm[key]);
            });
            //组装文件数据
            this.fileList.forEach(item => {
              formData.append('imgs', item.raw)
            });
            //异步提交需要等待时间
            this.sendFile(formData);
          } else {
            this.$message.error('error submit!!');
            return false;
          }
        });
      },
      sendFile(data){
        //提交前等待
        this.$axios({
          method: 'post',
          url: "shop/shop.action",
          data: data,
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(res => {
          if (res.data.code > 0) {
            this.$message.success(res.data.msg);
            this.resetForm("addForm");//重置表单
            this.fileList=[];//重置图像
          } else {
            this.$message.error(res.data.msg)
          }
        }).catch(err => {
          this.$message.warning(err);
        });
      },
      resetForm(formName) {
        //重置表单
        this.$refs[formName].resetFields();
        this.addForm.shopRemark = "";
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 6 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length} 个文件`)
      },
      beforeRemove(file, fileList) {
        if (this.$confirm(`确定移除 ${file.name}？`)) {
          this.fileList = fileList;
        }
      }
    },
    created() {
      this.getShopTypes();
    }
  }
</script>

<style scoped>

</style>
